package cn.com.ddapp.ddm.pay.alipay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.pay.PayCallback;
import cn.com.ddapp.ddm.util.TLog;


public class AlipayProvider{

	//商户PID
	public static final String PARTNER = "2088421664710272";
	//商户收款账号
	public static final String SELLER = "wing.chen@yzttec.com";
	//商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALLfuJAw56mRUUPL7DK7KOAGCAmgGToDWG4GS/PDN6QaaSImhkiAf6TsnqRSt/MyBZNUAw17LeOf78Ihe/hPAdvGec1x7xtzvBVikkeO61Z0Xs3+3SfCCJmDNDJhoeRbjAoB0SU0e3KPs7TWxc4q5q//WE5bimNa+XXg5NO8tZvjAgMBAAECgYAgHy7sreucNt1qGF/FSHjxqgOdfuOo2Frz/yt6je8bCCcjG9n3gSPrARcIGVaxVKVNrMOTkzBNdTZAHXU+xSlm+fZPF4VXQodGJJnw258l++HutwchPQnEo5fMP1Tskv/A5i+q4Ws+kY1txLB7fZggbVCKEUqigi4kpHkY1M1GyQJBAO3vw/XUNoKXcdP7/PPV0kab9xBgCJedipMf5cShReBoGdSx2ZRW08AmdLJeG49Un5OWAa+ksTzDCvlTyImnj58CQQDAdBaKK1Jms46cyhK2Z41KzUoQ7PcNHjcgtRgOt+z8Yk22IEtn+fyRCVE8nBKen8oLHYTynqLaIt3JGPzNQL09AkBCGvs2sV7zqV/WpYwBssZZF7vssMGyXfLCLXqIxsXDMyj6Du+EZxstp4GEjODbUYeEWYjeY8NaPlYuLzjoBcXBAkAs6Kn90gAngQztX2YgdGePJfp7mqBHyl443qlffeHqPxI9Rqnx+G7MdW0khJL/uu/NyjSk3QnJd0tjytXrG4lNAkBEWgQ2koEOKSgMAn3qq+PdoU2266CTEZowZ4xECAA4Iz1x8hGNpzSFwocTTy2hmUXtK9TFwhc0oJogLJsCD5xw";

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;
	
	public static final int PAY_SUCCESS = 0;
	
	public static final int PAY_FAIL = -1;
	
	public static final int PAY_CANNEL = 1;
	
	private Activity context;
	private PayObject payInfo;
	private PayCallback callback;
	
	public AlipayProvider(Activity context,PayObject payobejct,PayCallback callback){
		this.context = context;
		this.payInfo = payobejct;
		this.callback = callback;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				
				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();
				
				String resultStatus = payResult.getResultStatus();
				TLog.log("支付返回结果：" + resultStatus);

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					if(callback != null)
						callback.callback(PAY_SUCCESS);
				} else {
					if("6001".equals(resultStatus)){
						if(callback != null){
							callback.callback(PAY_CANNEL);
						}
					}else {
						if(callback != null){
							callback.callback(PAY_FAIL);
						}
					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(context, context.getString(R.string.check_result) + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 *  call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay() {
		// 订单
		String orderInfo = getOrderInfo(payInfo.getName(), payInfo.getBody(), payInfo.getPrice());

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(context);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Log.i("AlipayProvider", result);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(context);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(context);
		String version = payTask.getVersion();
		Toast.makeText(context, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + payInfo.getPrice() + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + payInfo.getNotify_url()
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"3d\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}
	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		System.out.println("订单号: "+payInfo.getOrderNo());
		return payInfo.getOrderNo();
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
